/*
 * @Author: sdorein sdorein@163.com
 * @Date: 2023-08-25 16:55:00
 * @LastEditors: sdorein sdorein@163.com
 * @LastEditTime: 2024-10-29 14:54:32
 * @FilePath: \server\src\server.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
const https = require('https');
const fs = require('fs');
const WebSocket = require('ws');
// 加载SSL/TLS证书
const server = https.createServer({
  cert: fs.readFileSync('path/to/rein-youerp.cn.pem'),
  key: fs.readFileSync('path/to/rein-youerp.cn.key'),
  passphrase: 'MIICtzCCAZ8CAQAwcjEXMBUGA1UEAxMOcmVpbi15b3VlcnAuY24xGjAYBgNVBAgTEVpoZWppYW5nIFByb3ZpbmNlMRYwFAYDVQQHEw1IYW5nemhvdSBDaXR5MQswCQYDVQQLEwJJVDEJMAcGA1UEChMAMQswCQYDVQQGEwJDTjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALfeCh9FNXmZZRG2YadItnjsODHcTCrlVJVlipIt4+KWyxv71+sOGVskjtIdeDWM9ItFzdyM6NOXC55STG1qOJgQxyPVf5ytFUMpKO7lmtoOAfxf6bAZnoYZQb2sV3OL1emCn7FEjLzIYBtSWh+EEJvEWdveOr8lhNyUvAqwASgMlIvtRSqZocMzS9yegW6n64qheEyEbQWxsKlsOux08ltB0N/DkmIwy8MJGuwX4aI4/c8WVnBCjiFfU+TwgRzac2x2I5XPeM91jqdqBI3F2L0hPWw5P3XbMQV+iEUuu/fUj4YDZg4MTBAO2Xnws/DlmPMgZmydjayQCnN4Zm9AClECAwEAAaAAMA0GCSqGSIb3DQEBCwUAA4IBAQB3zz5BY5uUWNKKESkBINTtZHrbksuM+PaImnavubBJj1vapjtFaTLUlWw19jn2MpGBVX5OhxARHW0zrTLRsAUNKVFHf6uZs4KG/CAt56lmyHTDTWdVWgBaeBCl4vX14fsKJFjSwY0fsHNrrSEitcEb68USnF6cWkMJVi52O1x/QP9zyVMOAxDArILMr0m+4WG1qmtIdLDa3nSsFZz1OxccPMcIe7YMDi7CvRiOHjIsU3jvW28nUpUhIyDb7a60Pkq70SCVnCjnPS32xbkp+VNf/muiICAc3lMNEPIeTZ9vUQOZENfF27yGKZkjzBLxoBYc7hJD+nq0f7V1AsW8tbXL' // 如果密钥文件是加密的
});
const wss = new WebSocket.Server({ maxPayload: 1024 * 1024, port: 8280 });
console.log("开始建立连接...")
wss.on('open', function open() {
  console.log('connected');
});

wss.on('close', function close() {
  console.log('disconnected');
});
let sedObj = {}
wss.on('connection', function connection(ws, req) {
  console.log("开始建立连接...", req.url);
  const ip = req.connection.remoteAddress;
  const port = req.connection.remotePort;
  const clientName = ip + port;
  const url = new URL("ws://localhost:8280" + req.url);
  console.log('url:', url);
  const searchParams = new URLSearchParams(url.search);
  const userid = searchParams.get('userid');
  console.log('searchParams:', searchParams, userid);
  console.log('%s is connected', userid);
  sedObj = {
    "clientName": userid,
    "message": "Welcome"
  }
  // 发送欢迎信息给客户端
  ws.send(JSON.stringify(sedObj));

  ws.on('message', function incoming(message) {
    console.log('received: %s from %s', message, userid);
    console.log(wss.clients.size, wss.clients);
    // 广播消息给所有客户端
    wss.clients.forEach(function each(client) {
      if (client.readyState === WebSocket.OPEN) {
        sedObj = {
          "clientName": userid,
          "message": message.toString()
        }
        console.log(sedObj);
        client.send(JSON.stringify(sedObj));// --clientName + " -> " + message
      }
    });

  });
  // 监听客户端断开连接事件
  ws.on('close', function close() {
    console.log(userid+':Client disconnected');
  });
});
console.log(`WebSocket建立完毕,服务端口：8280`)